const Koa = require('koa')
const server = new Koa();
const router = require('koa-router')()
const koaStatic = require('koa-static')
const proxy = require('koa2-proxy-middleware')
const fs = require('fs')
const path = require("path");
const resolve = (file) => path.resolve(__dirname, file);

const { createBundleRenderer } = require('vue-server-renderer');
const serverBundle = require('../dist/server/vue-ssr-server-bundle.json');
const clientManifest = require('../dist/client/vue-ssr-client-manifest.json');


const template = fs.readFileSync(resolve('./index.template.html'), 'utf-8');
const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false,
  template,
  clientManifest
});

// 代理后台请求
const proxyOptions = {
  targets: {
    '/api/(.*)': {
      target: 'http://localhost:3000',
      changeOrigin: true
    }
  }
}

server.use(proxy(proxyOptions))

// 中间件处理静态文件请求
server.use(koaStatic('./dist/client', { index: false }))

router.get('/', async (ctx, next) => {
  if (!ctx.url.startsWith('/api')) {
    ctx.set('Content-Type', 'text/html;charset=utf-8')

    const handleError = err => {
      console.log(err)
      if (err.code === 404) {
        ctx.status = 404
        ctx.body = '404 Page Not Found'
      } else {
        ctx.status = 500
        ctx.body = '500 Internal Server Error'
      }
    }
    const context = {
      url: ctx.url,
      title: 'vue ssr',
      meta: `
        <meta name="referrer" content="no-referrer">
      `
    }

    try {
      const html = await renderer.renderToString(context)
      ctx.status = 200
      ctx.body = html;
    } catch (error) {
      handleError(error);
    }
    next()
  }
})

server.use(router.routes()).use(router.allowedMethods())

server.listen(3333, () => {
  console.log('服务启动成功')
});
